<?php
class Application_Model_OrderItem extends Application_Model_DomainObject{
	
	protected $_id;
	
	protected $_orderId;
	
	protected $_price;
	
	protected $_productId;
	
	protected $_quantity;
	
	protected $_productName;
	
	protected $_comment;
        
        protected $_skuNo;

        protected $_status;

        protected $_description;
        
        protected $_taoBaoUrl;
        
        protected $_problemContent;//问题原因
        
        protected $_ckPass;
    /**
	 * 返回数据持久化对象
	 * @return Application_Model_DbTable_OrderItem
	 */
	private static function getDb(){
		return new Application_Model_DbTable_OrderItem(); 
	}
	
	/**
	 * 根据orderId返回一个orderItem数组
	 * @param int $orderId
	 * @return array
	 */
	public static function getByOrderId($orderId){
		return Application_Model_OrderItem::getDb()->queryAll(array('orderId'=>$orderId));
	}
    
    protected $_product;
    
    public function getProduct(){
        if($this->_product==NULL)
            $this->_product = new Application_Model_Product ($this->_productId);
        return $this->_product;
    }
    
    protected $_sku;
    public function getSku(){
        if($this->_sku==NULL && $this->_skuNo!=null && $this->_skuNo!='')
            $this->_sku = Application_Model_Sku::getBySkuNo($this->_skuNo);
        return $this->_sku;
    }
    
    private $image;
    public function getImage(){
        if($this->image!=NULL)
            return $this->image;
        
        if($this->getSku() != NULL)
            $this->image = $this->getSku ()->Image;
        
        if ($this->image == NULL)
            $this->image = $this->getProduct ()->Image;
        
        if ($this->image == NULL)
            $this->image = Application_Model_Product::DEFAULT_IMAGE;
        
        return $this->image;
    }
    
    public function getStatusText(){
        $names = array(1=>'缺货退款',2=>'质量退款',3=>'卖家延迟发货',4=>'取消并退款',NULL=>'',0=>'');
        return $names[$this->_status];
    }
    public function getbyproductd() {
        return Application_Model_Product::load($this->_productId);
    }
    /**
     * 获取OrderItem的URL地址
     * 1、先判断是否已经有淘宝推广的URL，如有则直接返回
     * 2、如没有，则通过API调用URL，再更新OrderItem的TaoBaoUrl字段。
     * @param type $product
     * @param type $orderItem
     * @return type
     */
    public static function GetTopUrl($product, $orderItem) {
        //return $product->url;
        if ($orderItem->taoBaoUrl != '') {
            //已经存在taobalUrl,则直接返回
            return $orderItem->taoBaoUrl;
        } else {
            //taoBaoUrl为空，通过API获取推广URL，并保存到orderItem->taoBalUrl.
            //return $product->url;
            $taobalReader = new Uuch_Reader_TaobaoReader();
            $topUrl = $taobalReader->getTopUrl($product->name,$product->url);
            if ($topUrl != NULL) {
                $orderItem->taoBaoUrl = $topUrl;
                $orderItem->save();
                return $orderItem->taoBaoUrl;
            } else {
                return $product->url;
            }
        }
    }
     public static  function singleRetuenMoney($id, $userid,$num) {
        $obj = Application_Model_OrderItem::load($id);
        if ($obj) {
            if ($obj->status == null) {
                try {
                    $db = Application_Model_OrderItem::getDb();
                    $db->beginTran();

                    $obj->status = 1;   //单个退款，状态为1
                    $obj->save();

                    $accountObj = Application_Model_UserAccount::load($userid);

                    $beforeMoney = $accountObj->money;

                    $accountObj->money = $accountObj->money + ($obj->price * $obj->quantity);
                    $accountObj->save();
                    Application_Model_Operate::intooperate(($obj->price * $obj->quantity), Application_Model_Operate::Type_singrefund, $obj->getOrderNum()."中商品".$id, $userid);
                    $dateCreated = date('Y-m-d H:i:s', time());
                    $comment = "代购订单:".$obj->getOrderNum().'中商品"'.mb_substr($obj->productName,0,8, 'utf-8').'···"单项退款';

                    $afterMoney = $beforeMoney + ($obj->price * $obj->quantity);

                    $userAccountHistory = new Application_Model_UserAccountHistory();
                    $userAccountHistory->type = 4;
                    $userAccountHistory->beforeMoney = $beforeMoney;
                    $userAccountHistory->afterMoney = $afterMoney;
                    $userAccountHistory->comment = $comment;
                    $userAccountHistory->dateCreated = $dateCreated;
                    $userAccountHistory->relaseId = $id;
                    $userAccountHistory->accountId = $userid;
                    $userAccountHistory->save();

                    $isAllReturn = true;
                    $order = Application_Model_Order::load($obj->orderId);
                    $itemList = $order->getshipdetail();
                    foreach ($itemList as $item) {
                        if ($item->status == 0) {
                            $isAllReturn = false;
                            break;
                        }
                    }

                    //判断是否全部都退款了，如果是则更新整个订单为 11 全部退款
                    if ($isAllReturn) {
                        //全都退款了，要更新整个订单，状态为11：全部退款
                        $order->status = 11;
                        $order->save();
                        if($num == 1){ // 1代表退运费
                            //检查是否有运费，如有，则把运费也退回去
                            $shipFee = (int) ($order->shipFee);
                            if ($shipFee > 0) {
                                $beforeMoney = $accountObj->money;

                                $accountObj->money = $accountObj->money + $shipFee;
                                $accountObj->save();
                                Application_Model_Operate::intooperate($shipFee, Application_Model_Operate::Type_shipFeerefund, $obj->getOrderNum()."中商品".$id, $userid);
                                $dateCreated = date('Y-m-d H:i:s', time());
                                $comment = "代购订单:".$obj->getOrderNum().'商品运费退款';

                                $afterMoney = $beforeMoney + $shipFee;

                                $userAccountHistory = new Application_Model_UserAccountHistory();
                                $userAccountHistory->type = 4;
                                $userAccountHistory->beforeMoney = $beforeMoney;
                                $userAccountHistory->afterMoney = $afterMoney;
                                $userAccountHistory->comment = $comment;
                                $userAccountHistory->dateCreated = $dateCreated;
                                $userAccountHistory->relaseId = $id;
                                $userAccountHistory->accountId = $userid;
                                $userAccountHistory->save();
                            }
                        }
                    } else {
                        //状态：12 部分退款
                        $order->status = 12;
                        $order->save();
                    }

                    $db->commit();
                } catch (Exception $ex) {
                    $db->rollBack();
                    return 0;
                }

                return 1;
            }
        } else {
            return 0;
        }
    }
     public function getOrderNum()
    {
        $result = Application_Model_Order::load($this->_orderId);
        return 'U2013'.$result->id.substr($result->dateCreated,17,1);
    }
    public static function countItem($id)
    {
        $result = self::load($id);
        if($result){
            $where[" orderId = "] = $result->orderId;
            $where[" and status is null and "] = 1;//1代表已经退款
            $countNum = self::getDao()->queryAll($where);
            $num = count($countNum);
        }else{
            $num = 0;
        }
        return $num;
    }
}